<?php

class Register extends Controller 
{
	var $uid;
	var $tpl;

	function setVars()
	{
		$this->tpl['title'] = "Registration";
		$this->tpl['head'] = '';
        $this->tpl['sidebar'] = '';
	}
	
	function __construct()
	{
		parent::Controller();
		$this->setVars();
		log_message('debug', "Contact->Registration->email: Controler Class Initialized");
        //$this->output->enable_profiler(TRUE);
	}

/*****************************************************************\
|               Register User
\*****************************************************************/	

	function index() 
	{
		if(isset($_POST['Alias']))
		{
			$this->postCheck();
		}
		else
		{
            $this->tpl['countryOptions'] = $this->country_options();
            $this->load->view('contact/register', $this->tpl);
		}
	}

	function postCheck()
	{
		log_message('debug', "Register email: Post check");
		$this->load->library('validation');
		$rules['Alias']			= "trim|required|min_length[4]|max_length[20]|xss_clean";
		$rules['eMail']			= "trim|required|valid_email|xss_clean";
		$rules['Country']		= "trim|required|xss_clean";
		$fields['Country']    	= 'Country';
		$this->validation->set_rules($rules);
		$this->validation->set_fields($fields);
		if ($this->validation->run() == FALSE)
		{
            $this->tpl['countryOptions'] = $this->country_options($this->validation->Country);
			$this->load->view('contact/register', $this->tpl);
		}
		else
		{
            $email = $this->validation->eMail;
            $alias = $this->validation->Alias;
            $this->db->select('id, eMail')->from('contact_people')->where('eMail', $this->validation->eMail)->limit(1);
			$query = $this->db->get();
			if ($query->num_rows() > 0)
			{
                $people_row = $query->row();
                $this->db->select('Alias')->from('contact_user')->where('people_id', $people_row->id)->limit(1);
                $query = $this->db->get();
                if ($query->num_rows() > 0)
                {
                    $user_row = $query->row();
                    if (strcasecmp($alias, $user_row->Alias) == 0) {
                        $alias_match = "And your Alias and eMail match"; 
                    }else{
                        $alias_match = "But your Alias and eMail don't match";
                    }
                    $this->msg->setError('You already have an account.');
                    $this->msg->setMsg($alias_match);
                    $this->msg->setMsg('Try to login');
                    $this->load->view('contact/login', $this->tpl);
                    //redirect('contact/login', 'location');
                }
                else
                {
                    $this->pid = $people_row->id;
                    $this->user_create();
                    redirect('contact/person', 'location'); 
                }
            }
            else
            {
                $email = $this->validation->eMail;
                $this->sql_people = "INSERT INTO `contact_people` (`eMail`, `Country`) 
                                     VALUES ('$email', '$this->Country');";
                $this->pid = $this->db->insert_id();
                $this->user_create();
				#redirect('account/secquestion', 'location');            
                #TODO: $this->Account->SendPass($query->alias, $email, $this->activation_key);
                redirect('contact/person', 'location');
            }
		}
	}
	
    
    function user_create()
    {
        $this->load->helper('string');
        $CTZ = $this->session->userdata('CTZ');
        $this->Country = $CTZ[$this->validation->Country]['FIPS'];
        $TZ = $CTZ[$this->validation->Country]['TZ_Linux'];
        $this->session->unset_userdata('CTZ');
        $this->load->helper('string');
        $k = $this->activation_key = random_string('unique');
        $p = random_string('alnum', 6);
        $ip = $this->fun->getip();
        $d = date("Y-m-d H:i:s");
        $a = $this->validation->Alias;
        $data = array(
                'people_id' =>$this->pid, 
                'Alias'     =>$a, 
                'Password'  =>$p, 
                'timezone'  =>$TZ, 
                'IP'        =>$ip, 
                'activation_key'=>$k, 
                'first'     =>$d
            );
        if(!isset($this->pid))unset($data['people_id']);
        $this->db->insert('contact_user', $data);
        $data['uid'] = $this->db->insert_id();
        $this->session_set($data);
    }

    function session_set($data)
    {
        $data['logged_in'] = FALSE;
        $data = (object) $data;
        $this->session->set_userdata($data);
        $this->session->unset_userdata('CTZ');
    }
    
    function country_options($selected = '')
	{
		$output = '<select name="Country">';
		$output .= "<option value=\"\">--Location by Timezone--</option>\n";
		$tz = $this->session->userdata('TZ');
		if(isset($tz))
		{
			$sql = "
			SELECT places_timezone.id, FIPS, TZ_Linux, Country 
			FROM places_timezone
			JOIN (places_country) 
			ON (places_timezone.ISO3166 = places_country.ISO3166)
			WHERE TZ = '$tz'
			";
		}
		else
		{
			$sql = "
			SELECT places_timezone.id, FIPS, TZ_Linux, Country 
			FROM places_timezone
			JOIN (places_country) 
			ON (places_timezone.ISO3166 = places_country.ISO3166)
			";
		}
		
		$query = $this->db->query($sql);
		foreach ($query->result() as $row)
		{
			if(isset($tz))
			{
				$this->TZ_Linux = $row->TZ_Linux;
				$d['CTZ'][$row->id]['TZ_Linux'] = $row->TZ_Linux;
				$d['CTZ'][$row->id]['FIPS'] = $row->FIPS;
				$this->session->set_userdata($d);
				$l = strstr($row->TZ_Linux, '/');
				$c = $row->Country;
				$c = $c.$l;
			}
            $sel = ($selected != $row->id) ? '' : ' selected="selected"';
            $output .= "<option value=\"$row->id\" $sel>$c</option>\n";
		}
		$output .= '</select>'; 
		return $output;		
	}
}
?>
